﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using xiaodingmarket_Domain.Models;

namespace Identitymodels.Authorization
{
    public class JwtToken
    {
        //现获取token的方法
        //iss ： jwt签发者   sub：jwt所面向的用户    aud：接收jwt的一方
        public async Task<string> GetJwtToken(string name, string id, bool hasCreate, string userrole, IConfiguration _configuration)
        {
            //判断是注册还是登陆，注册的话角色是默认普通用户，登陆需要去数据库查询
            if (hasCreate)
            {
                
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name,name),//添加了角色信息
                    new Claim(ClaimTypes.Role, "superAdmin"),
                    new Claim(JwtRegisteredClaimNames.Jti, id),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(TimeSpan.FromSeconds(60 * 60 * 24).TotalSeconds).ToString())//一天过期
                };
                //用户标识(可能用来写入sub)
                var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                identity.AddClaims(claims);

                var section = _configuration.GetSection("TokenManagement");
                //取密钥
                var symmetricKeyAsBase64 = section.GetSection("Secret").Value;
                var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
                var signingKey = new SymmetricSecurityKey(keyByteArray);


                var now = DateTime.Now;
                // 实例化JwtSecurityToken
                var jwt = new JwtSecurityToken(
                    issuer: section.GetSection("Issuer").Value,
                    audience: section.GetSection("Audience").Value,
                    claims: claims,
                    notBefore: now,
                    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature),
                    expires: now.Add(TimeSpan.FromSeconds(60 * 60 * 24))

                );
                // 生成 Token
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
                return encodedJwt;
            }
            else
            {
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name,name),//注册默认角色信息
                    new Claim(ClaimTypes.Role, userrole),
                    new Claim(JwtRegisteredClaimNames.Jti, id),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(TimeSpan.FromSeconds(60 * 60 * 24).TotalSeconds).ToString())//一天过期
                };
                //用户标识(可能用来写入sub)
                var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                identity.AddClaims(claims);

                var section = _configuration.GetSection("TokenManagement");
                //取密钥
                var symmetricKeyAsBase64 = section.GetSection("Secret").Value;
                var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
                var signingKey = new SymmetricSecurityKey(keyByteArray);


                var now = DateTime.Now;
                //实例化JwtSecurityToken
               var jwt = new JwtSecurityToken(
                   issuer: section.GetSection("Issuer").Value,
                   audience: section.GetSection("Audience").Value,
                   claims: claims,
                   notBefore: now,
                   signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature),
                   expires: now.Add(TimeSpan.FromSeconds(60 * 60 * 24))

               );
                //SecurityToken tokenDescriptor = new SecurityToken
                //{
                //    Subject = identity,
                //    Issuer = section.GetSection("Issuer").Value,
                //    Audience = section.GetSection("Audience").Value,
                //    Expires = now.Add(TimeSpan.FromSeconds(60 * 60 * 24)),
                //    SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature)
                //};
                // 生成 Token
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                return encodedJwt;
            }

        }
        public static TokenModelJwt SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role;
            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            var tm = new TokenModelJwt
            {
                Uid = int.Parse(jwtToken.Id),
                Role = role != null ? role.ToString() : "",
            };
            return tm;
        }
    }

    public class TokenModelJwt
    {
        /// <summary>
        /// Id
        /// </summary>
        public long Uid { get; set; }
        /// <summary>
        /// 角色
        /// </summary>
        public string Role { get; set; }
    }
}
